package com.spark.market.controller;

import com.spark.market.api.request.OrderCreateParam;
import com.spark.market.api.utils.ResponseResult;
import com.spark.market.api.utils.ResponseUtil;
import com.spark.market.common.exception.BusinessException;
import com.spark.market.common.exception.EmBusinessError;
import com.spark.market.common.utils.AssertUtils;
import com.spark.market.common.utils.CodeUtil;
import com.spark.market.service.OrderQueryCoreService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("order/query")
public class OrderQueryController extends BaseController{
    @Resource
    OrderQueryCoreService orderQueryCoreService;
    @Resource
    RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/fun_queryPromoToken")
    public ResponseResult<String> queryPromoToken(@RequestBody OrderCreateParam param){
        AssertUtils.isNotNull(param, "param is null");
        return ResponseUtil.createSuccessResult(orderQueryCoreService.queryPromoToken(param));
    }

    /**
     * 获取验证码
     * @param response
     * @param userId
     * @return
     */
    @PostMapping("/fun_generateToken/{userId}")
    public ResponseResult<Object> generateToken(HttpServletResponse response, @PathVariable("userId") String userId){
        final Map<String, Object> map = CodeUtil.generateCodeAndPic();
        try {
            ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", response.getOutputStream());
            redisTemplate.opsForValue().set("verify_code_" + userId, map.get("code"));
        } catch (IOException e) {
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
        }
        return ResponseUtil.createSuccessResult(null,"获取成功");
    }
}
